package com.ycsj.goldmedalnewconcept.fragment;

import java.io.IOException;
import java.util.ArrayList;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.CycleInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.activity.LoginActivity;
import com.ycsj.goldmedalnewconcept.activity.NewWordsYuXiActivity;
import com.ycsj.goldmedalnewconcept.activity.WordFuxiAndroidActivity;
import com.ycsj.goldmedalnewconcept.activity.WordsFuxiActivity;
//import com.ycsj.goldmedalnewconcept.activity.WordsYuxiActivity;
import com.ycsj.goldmedalnewconcept.bean.WordSecondListInfo;
import com.ycsj.goldmedalnewconcept.bean.WordSecondResp;
import com.ycsj.goldmedalnewconcept.bean.WordSecondResq2;
import com.ycsj.goldmedalnewconcept.bean.mineBasicInfoResp2;
import com.ycsj.goldmedalnewconcept.constant.ConfigConstant;
import com.ycsj.goldmedalnewconcept.constant.NetConstant;
import com.ycsj.goldmedalnewconcept.utils.SPUtil;
import com.ycsj.goldmedalnewconcept.utils.SPUtils;
import com.ycsj.goldmedalnewconcept.view.FerrisWheelLayout;

/**
 * 首页fragment ViewPager tab
 * 
 * @author dewyze 轮循球
 */
public class PreviewSecondFragment extends BaseFragment {

	private static final String TAG = "PreviewSecondFragment";
	private Activity mActivity;
	private TextView mMsgTv;
	private ImageView iv_person;
	private String mMsgName;
	Handler handler = new Handler();

	public void setMsgName(String msgName) {
		this.mMsgName = msgName;
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		this.mActivity = activity;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	int j = 8;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_preview_second,
				container, false);
		fwl = (FerrisWheelLayout) view.findViewById(R.id.fw_fwl);
		iv_person = (ImageView) view.findViewById(R.id.iv_person);
		fwl.setFirstNum(SPUtils.getInt(getActivity(), "firstNum"));

		tv_title = (TextView) view.findViewById(R.id.tv_title);
		SPUtils.put(getActivity(), ConfigConstant.CURRENTFRAGMENT, TAG);
		int GRADE_ID = getArguments().getInt("GRADE_ID");
		firstNum = getArguments().getInt("firstNum");
		String GRADE_NAME = getArguments().getString("GRADE_NAME");

		if (!SPUtils.getBoolean(getActivity(), ConfigConstant.IS_LOGIN_ON)) {

			fwl.setcount(4);
			fwl.setVisibility(View.VISIBLE);
			for (int i = 8; i > 3; i--) {
				fwl.getChildAt(i).setVisibility(View.GONE);

			}

		}

		OkHttpClient mOkHttpClient = new OkHttpClient();
		// 创建一个Request
		final Request request = new Request.Builder().url(
				NetConstant.ycsj_platform
						+ "?type=1&gradeid="
						+ GRADE_ID
						+ "&account="
						+ SPUtils.getString(getActivity(),
								ConfigConstant.USERNAME) + "&role="
						+ SPUtil.getString(getActivity(), "role", "0")).build();

		Log.e("test",
				"url="
						+ NetConstant.WORDLEARNING
						+ "/LevelTwo.aspx?gradeid="
						+ GRADE_ID
						+ "&account="
						+ SPUtils.getString(getActivity(),
								ConfigConstant.USERNAME)
						+ "&usertoken="
						+ SPUtils.getString(getActivity(),
								ConfigConstant.USERTOKEN));
		// new call
		Call call = mOkHttpClient.newCall(request);
		// 请求加入调度
		call.enqueue(new Callback() {

			@Override
			public void onFailure(Request arg0, IOException arg1) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onResponse(Response arg0) throws IOException {
				// TODO Auto-generated method stub
				String json = arg0.body().string();
				// Toast.makeText(getActivity(), "onSuccess", 0).show();
				Log.e("test", json);

				Gson gson = new Gson();
				// // 2 使用gson对象的方法
				if ("1".equals(gson.fromJson(json, mineBasicInfoResp2.class).result)
						|| "2".equals(gson
								.fromJson(json, WordSecondResq2.class).RESULTTYPE)) {

				} else {
					WordSecondResp wordSecondResp = gson.fromJson(json,
							WordSecondResp.class);
					if (null != wordSecondResp) {

						list.addAll(wordSecondResp.LIST);
					}
					if (list.size() == 18) {
						SPUtils.put(getActivity(), "UnitCount", 18);
					} else {
						SPUtils.put(getActivity(), "UnitCount", 4);
					}

					handler.postDelayed(new Runnable() {

						@Override
						public void run() {
							if (!SPUtils.getBoolean(getActivity(),
									ConfigConstant.IS_LOGIN_ON)) {

								fwl.setcount(4);
								progressBar.setVisibility(progressBar.GONE);
								fwl.setVisibility(View.VISIBLE);
								for (int i = 8; i > 3; i--) {
									fwl.getChildAt(i).setVisibility(View.GONE);

								}

							} else {
								fwl.setcount(SPUtils.getInt(getActivity(),
										"UnitCount"));

								Log.e("LoginActivity", "ccccc" + list.size());

								progressBar.setVisibility(progressBar.GONE);
								fwl.setVisibility(View.VISIBLE);

								for (int i = 8; i > list.size() - 1; i--) {
									Log.e("LoginActivity", "ccccc=" + i);
									fwl.getChildAt(i).setVisibility(View.GONE);
								}
							}

							// for (int i = 0; i <9; i++) {
							//
							// fwl.getChildAt(i).setVisibility(View.VISIBLE);
							//
							// Log.e("test", "ccccc"+i);
							// }
						}
					}, 2000);

				}
			}
		}

		);

		tv_title.setText(GRADE_NAME);

		return view;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);

		initViews(view);

	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		initDisplay();
	}

	private void initViews(View view) {
		progressBar = (RelativeLayout) view.findViewById(R.id.progressBar);

		TextView tv_back = (TextView) view.findViewById(R.id.tv_back);
		tv_back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				FragmentTransaction ft = getFragmentManager()
						.beginTransaction();
				HomeFragment gf = new HomeFragment();
				ft.replace(R.id.center_layout, gf);
				ft.addToBackStack(null);
				ft.commit();
			}
		});

		fwl.setVisibility(View.INVISIBLE);

		if (SPUtils.getInt(getActivity(), "UnitCount") > 4) {
			int childCount = fwl.getChildCount();
			for (int i = 0; i < childCount; i++) {
				fwl.getChildAt(i).setOnClickListener(toastTagOcl);
			}
		} else {
			int childCount = 4;
			for (int i = 0; i < childCount; i++) {
				fwl.getChildAt(i).setOnClickListener(toastTagOcl);
			}
		}

	}

	private void initDisplay() {
	}

	@Override
	public String getFragmentName() {
		return TAG;
	}

	public OnTouchListener onTouch = new OnTouchListener() {

		@Override
		public boolean onTouch(View v, MotionEvent event) {

			switch (event.getAction()) {
			case MotionEvent.ACTION_DOWN:

				break;
			case MotionEvent.ACTION_UP:

				Animation shakeAnim = AnimationUtils.loadAnimation(
						getActivity(), R.anim.shake);
				v.startAnimation(shakeAnim);

				break;
			}
			return true;
		}

	};
	private FerrisWheelLayout fwl;

	public Animation shakeAnimation(int CycleTimes) {
		Animation translateAnimation = new TranslateAnimation(0, 0, -10, 10);
		translateAnimation.setInterpolator(new CycleInterpolator(CycleTimes));
		translateAnimation.setDuration(1000);
		return translateAnimation;
	}

	private OnClickListener toastTagOcl = new OnClickListener() {

		@Override
		public void onClick(View v) {
			TextView tv = (TextView) v;

			final Dialog dialog = new Dialog(getActivity(), R.style.MyDialog);
            //设置它的ContentView
            dialog.setContentView(R.layout.dialog);
            dialog.setCanceledOnTouchOutside(true);
            TextView tv_dialog_unit = (TextView) dialog.findViewById(R.id.tv_dialog_unit);
            
            
            
            
            Button dialog_button_cancel = (Button) dialog.findViewById(R.id.dialog_button_cancel);
            Button dialog_button_ok = (Button) dialog.findViewById(R.id.dialog_button_ok);
            final int index=Integer.parseInt((String) tv.getText().toString())-SPUtils.getInt(getActivity(), "firstNum");
           
            if(list.isEmpty()){
//            	Toast.makeText(getActivity(), "网络状态不佳！！！", 0).show();
            	return;
            }else{
            tv_dialog_unit.setText(list.get(index).LESSON_NAME);
            dialog_button_cancel.setOnClickListener(new OnClickListener() {
				//预习
				@Override
				public void onClick(View v) {
					
						Intent intent = new Intent(getActivity(),
								NewWordsYuXiActivity.class);
						
						intent.putExtra("lESSON_ID", list.get(index).LESSON_ID);
						startActivity(intent);
						dialog.cancel();
						// }

					}
				});
				dialog_button_ok.setOnClickListener(new OnClickListener() {
					// 检测
					@Override
					public void onClick(View v) {

						// if(!SPUtils.getBoolean(getActivity(),
						// ConfigConstant.IS_LOGIN_ON)){
						// //getFragmentManager().beginTransaction().addToBackStack(null).replace(R.id.main_fragment_container,
						// new NotLoggedFragment()).commit();
						// Intent intent = new
						// Intent(getActivity(),LoginActivity.class);
						// startActivity(intent);
						// }else{
						// Intent intent = new
						// Intent(getActivity(),WordsFuxiActivity.class);
						Intent intent = new Intent(getActivity(),
								WordsFuxiActivity.class);
//						Intent intent = new Intent(getActivity(),
//								WordFuxiAndroidActivity.class);
						
						intent.putExtra("lESSON_ID", list.get(index).LESSON_ID);
						intent.putExtra("LESSON_NAME",
								list.get(index).LESSON_NAME);
						startActivity(intent);
						dialog.cancel();
						// }

					}
				});
				dialog.show();
			}
		}
	};
	private ArrayList<WordSecondListInfo> list = new ArrayList<WordSecondListInfo>();
	private RequestCallBack<String> callBack = new RequestCallBack<String>() {

		@Override
		public void onSuccess(ResponseInfo<String> responseInfo) {
			// TODO Auto-generated method stub
			String json = responseInfo.result;
			// Toast.makeText(getActivity(), "onSuccess", 0).show();
			// Log.i("test", json);

			Gson gson = new Gson();
			// // 2 使用gson对象的方法
			if ("1".equals(gson.fromJson(json, mineBasicInfoResp2.class).result)
					|| "2".equals(gson.fromJson(json, WordSecondResq2.class).RESULTTYPE)) {

			} else {
				WordSecondResp wordSecondResp = gson.fromJson(json,
						WordSecondResp.class);
				list.addAll(wordSecondResp.LIST);
				// lv_test_second.setAdapter(new MyAdapter(list));
			}
		}

		@Override
		public void onFailure(HttpException error, String msg) {
			// TODO Auto-generated method stub
			Toast.makeText(getActivity(), msg, 0).show();
		}
	};
	private TextView tv_title;
	private int firstNum;
	private RelativeLayout progressBar;

}
